<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" @change="deptChange1" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" placeholder="请选择" clearable>
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="通道名称">
          <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 120px;" placeholder="停车场名称"/>
        </el-form-item>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:passway:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row >
      <!-- <el-table-column align="center" label="通道id" prop="id" /> -->

      <el-table-column align="center" label="通道名称" prop="name" />

      <el-table-column align="center" label="停车场" prop="parkName"/>
      <el-table-column align="center" label="创建时间" prop="createTime"/>

      <el-table-column align="center" label="所属机构" prop="departmentName"/>

      <!-- <el-table-column align="center" label="通道类型" prop="type">
        <template slot-scope="scope">
          <el-tag >{{ getType(scope.row.type) }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:passway:update']"
            type="primary"
            size="small"
            @click="startEditPassway(scope.row)">编辑</el-button>
            <!-- <el-button type="primary" size="small" @click="deletePassway(scope.row.name, scope.row.id)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'添加通道':'修改通道'" :visible.sync="dialogFormVisible" width="28%">
      <el-form ref="dialogForm" :inline="true" :rules="formRules" :model="dialogForm" align="center" label-width="120px">
        <el-form-item label=" 机构  " prop="departmentId">
          <el-select v-model="dialogForm.departmentId" :disabled="dialogType === 2"
          placeholder="请选择" @change="deptChange">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label=" 停车场  " prop="parkId">
          <el-select v-model="dialogForm.parkId" :disabled="dialogType === 2" placeholder="请选择">
            <el-option
              v-for="item in parkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label=" 通道名称  " prop="name">
          <el-input v-model="dialogForm.name" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm');">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, deletePassway, createPassway, updatePassway,passwayDetail } from '@/api/passway'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Passway',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      downloadLoading: false,
      dialogTitle: '温馨提示',
      dialogFormVisible: false,
      delDialogFormVisible: false,
      dialogForm: {},
      dialogType: 1,
      departmentList: [],
      parkList: [],
      allParkList: [],
      formRules: {
        departmentId: [{ required: true, message: '请选择机构', validator: this.checkSelected, trigger: 'change' }],
        parkId: [{ required: true, message: '请选择停车场', validator: this.checkSelected, trigger: 'change' }],
        name: [{ required: true, message: '请输入通道名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDepartmentList()
    this.getList()
  },
  methods: {
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId,parkType:1})
      return res.data || []
    },
    async deptChange1(e){//机构下拉选择
      let listQuery = {...this.listQuery}
      listQuery.parkId = ''
      this.listQuery = {...listQuery}
      if(!e) return this.allParkList = []
      this.allParkList = await this.getListAuthPark(e)
    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },

    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getType(type) {
      if (type === 1) {
        return '通用通道'
      }
      return '长租通道'
    },
    deletePassway(name, parkId) {
      this.$confirm(`您确定删除通道：${name}`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePassway({ id: parkId }).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {
      this.dialogForm = {}
      this.dialogFormVisible = true
      this.dialogType = 1
      this.parkList = []
      this.$nextTick(() => {
        this.$refs.dialogForm.clearValidate()
      })
      this.getDepartmentList()
    },
    confirmEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType === 1) {
            createPassway(this.dialogForm).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            updatePassway(this.dialogForm).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    reset() {
      this.dialogForm = {};
      this.resetForm("dialogForm");
    },
    startEditPassway(row) {
      this.reset();
      passwayDetail(row.id).then(async response => {
        this.dialogForm = response.data || {};
        this.dialogFormVisible = true
        this.dialogType = 2
        this.parkList = []
        this.getDepartmentList()
        this.parkList = await this.getListAuthPark(this.dialogForm.departmentId)
      });
    },
    deptChange(event){//机构下拉改变事件
      let dialogForm = {...this.dialogForm}
      dialogForm.parkId = ''
      this.dialogForm = {...dialogForm}
      this.selectDepartmentId(event)
    },
    async selectDepartmentId(event) {
      this.parkList = []
      this.parkList = await this.getListAuthPark(event)
    }

  }
}
</script>
